﻿using Cms.Core.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace Cms.Core.Infrastructure.Runtime.Session
{
    public static class CmsSessionExtensions 
    {
        public static Guid? GetUserId(this ICmsSession session)
        {

            if (!session.UserId.HasValue || session.UserId == Guid.Empty)
            {
                throw new Exception("Session.UserId 为空，没有登录!!");
            }
            return session.UserId.Value;
        }

        public static Guid? GetUserIdOrDefault(this ICmsSession session,Guid? value)
        {

            if (!session.UserId.HasValue || session.UserId == Guid.Empty)
            {
               return value;
            }
            return session.UserId.Value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string[] GetUserRoleName(this ICmsSession session, string type = ClaimTypes.Role)
        {

            var claims  = session as ClaimsCmsSession;
            return claims?.PrincipalAccessor.Principal?.Claims.Where(o => o.Type == type).Select(o => o.Value).ToArray();
        }

        /// <summary>
        /// 是否管理员
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        public static bool IsAdministrators(this ICmsSession session)
        {
            return session.GetUserRoleName().Any(o => o == Keys.administratorsName);
        }
    }
}
